/*
 * @Author: dadadaXU 1413107032@qq.com
 * @Date: 2025-01-24 16:13:28
 * @LastEditors: dadadaXU 1413107032@qq.com
 * @LastEditTime: 2025-01-24 16:35:25
 * @FilePath: \LeetCode\160.相交链表.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @lc app=leetcode.cn id=160 lang=cpp
 *
 * [160] 相交链表
 * 方法：使用双指针
 * - 遍历长度为 A + B
 * - 问题：int count = 2; 多余 -> 遍历到结尾：p_A == p_B == nullptr
 */

#include <iostream>

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

// @lc code=start
class Solution
{
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
    {
        ListNode *p_A = headA, *p_B = headB;
        int count = 2; // 统计 p_A == nullptr 的次数

        while (p_A != p_B && count > 0)
        {
            p_A = (p_A == nullptr) ? headB : p_A->next;
            p_B = (p_B == nullptr) ? headA : p_B->next;
            if (p_A == nullptr)
                count--;
        }

        return (count == 0) ? nullptr : p_A;
    }

    ListNode *getIntersectionNode_00(ListNode *headA, ListNode *headB)
    {
        ListNode *p_A = headA, *p_B = headB;

        while (p_A != p_B)
        {
            p_A = (p_A == nullptr) ? headB : p_A->next;
            p_B = (p_B == nullptr) ? headA : p_B->next;
        }

        return p_A;
    }
};
// @lc code=end
